<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cms:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cms:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cms:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模版编号" align="center" prop="id" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="关联规格" align="center" prop="specIds" >
        <template slot-scope="scope">
          {{transformData(scope.row.specIds)}}
        </template>
      </el-table-column>
      <el-table-column label="关联品牌" align="center" prop="brandIds" >
        <template slot-scope="scope">
          {{transformData(scope.row.brandIds)}}
        </template>
      </el-table-column>
      <el-table-column label="自定义属性" align="center" prop="customAttributeItems" >
        <template slot-scope="scope">
          {{transformData(scope.row.customAttributeItems)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模版管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="关联规格" prop="specIds">
          <el-select v-model="selectSpecIds" multiple placeholder="请选择规格" style="width: 100%">
            <el-option
              v-for="spec in specList"
              :key="spec.id"
              :label="spec.specName"
              :value="spec.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联品牌" prop="brandIds">
          <el-select v-model="selectBrandIds" multiple placeholder="请选择品牌" style="width: 100%">
            <el-option
              v-for="brand in brandList"
              :key="brand.id"
              :label="brand.brandName"
              :value="brand.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拓展属性" prop="customAttributeItems">
          <el-button type="primary" @click="tableData.push({})">新增拓展属性</el-button>
          <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
              label="属性名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.text"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="180">
              <template slot-scope="scope">
                <el-button type="danger" @click="removeItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/cms/template";
import { listAllBrand } from "@/api/cms/brand";
import { listAllSpec } from "@/api/cms/spec";

export default {
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模版管理表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      brandList:[],
      selectBrandIds:[],
      brandMap:{
      },
      specList:[],
      selectSpecIds:[],
      specMap:{
      },
      tableData:[{}]
    };
  },
  created() {
    this.getList();

    listAllBrand().then(res=>{
      this.brandList = res.rows;
      for(var i in this.brandList){
        this.brandMap[this.brandList[i].id] = this.brandList[i].brandName
      }
    });

    listAllSpec().then(res=>{
      this.specList = res.rows;
      for(var i in this.specList){
        this.specMap[this.specList[i].id] = this.specList[i].specName
      }
    });
  },
  methods: {
    /** 查询模版管理列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        specIds: null,
        brandIds: null,
        customAttributeItems: null
      };

      this.selectBrandIds = [];
      this.selectSpecIds = [];
      this.tableData = [{}]

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模版管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模版管理";

        //处理拓展属性回显
        this.tableData = JSON.parse(this.form.customAttributeItems)

        //处理品牌回显
        var brandArray = JSON.parse(this.form.brandIds)
        var brandIdsArray = [];
        for(var i in brandArray){
          brandIdsArray.push(brandArray[i].id)
        }
        this.selectBrandIds = brandIdsArray


        //处理规格回显
        var specArray = JSON.parse(this.form.specIds)
        var specIdsArray = [];
        for(var i in specArray){
          specIdsArray.push(specArray[i].id)
        }
        this.selectSpecIds = specIdsArray


      });
    },
    /** 提交按钮 */
    submitForm() {
      //对品牌下拉框数据进行转换   [1,2,3]--->[{id:1,text:'xxxxx'},{},{}]
      var brandArray = []
      for(var i in this.selectBrandIds){
        var id = this.selectBrandIds[i];
        var brandName = this.brandMap[id];
        brandArray.push({id:id,text:brandName})
      }
      this.form.brandIds = JSON.stringify(brandArray)


      //对规格下拉框数据进行转换   [1,2,3]--->[{id:1,text:'xxxxx'},{},{}]
      var specArray = []
      for(var i in this.selectSpecIds){
        var id = this.selectSpecIds[i];
        var specName = this.specMap[id];
        specArray.push({id:id,text:specName})
      }
      this.form.specIds = JSON.stringify(specArray)

      //对拓展属性数据进行转换
      this.form.customAttributeItems = JSON.stringify(this.tableData)


      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模版管理编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cms/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    transformData(obj){
      var result = "";
      var array = JSON.parse(obj);
      for(var i in array){
        result += ","+array[i].text;
      }
      result = result.substring(1);
      return result;
    },
    removeItem(row){
      var index = this.tableData.indexOf(row)
      this.tableData.splice(index,1);
      if(this.tableData.length == 0){
        this.tableData.push({})
      }
    }
  }
};
</script>
